#! /usr/bin/python
import os,sys,string,subprocess

FTP_SERVER_URL = "ftp://192.168.0.18"
PROJ_BUILDS_URL = "http://192.168.0.18:8080/dashboard/tab/builds"
CC_BUILD_DETAIL_URL = "http://192.168.0.18:8080/dashboard/tab/build/detail"

class Target():
    def __init__(self, name, ftp_rpath, local_rpath):
        self.name = name
        self.ftp_rpath = ftp_rpath
        self.local_rpath = local_rpath
        
def exec_shell_cmd(cmd, is_stdout=True):
    ret_val = None 
    ret_stdout = None
    ret_stderr = None
    if not cmd: return (ret_val, ret_stdout, ret_stderr)
    try:
        if is_stdout:
            ret_val = subprocess.Popen(cmd, shell=True, stdout=None).wait()
        else:
            p1 = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
            ret_val = p1.wait()
            (ret_stdout,ret_stderr) = p1.communicate()
    except KeyboardInterrupt:
        print "\n==== User interrupt cmd's process! ===="
    except OSError or ValueError:
        print "Error: Cannot execute this command!"
    return (ret_val, ret_stdout, ret_stderr)
    
def action_on_get(target_selected, proj_selected, version_folder_selected):
    if not version_folder_selected:
        print "None version is selected!"
        return -1
    try:
        for tgt in target_selected:
            if isinstance(tgt, Target):
                get_target_cmd = "wget -m %s/%s/%s/%s  -nH -nv --cut-dirs=4 -P %s" %(FTP_SERVER_URL, proj_selected, version_folder_selected, tgt.ftp_rpath, tgt.local_rpath)
                exec_shell_cmd(get_target_cmd)[0]
            else:
                print "Error: tgt is not instance of TARGET!"
                return -1
    except IndexError:
        print "Error: get target %s failed!" %(tgt.name)
        return -1
            
def version_choice_menu(target_selected, proj_selected):
    if not proj_selected:
        print "None proj is selected!"
        return -1
        
    get_ver_folder_list_cmd = """wget -q -c -O - %s/%s | grep -e '%s_[[:digit:]].*\+M$' -A 2 | grep ftp: | sed -e 's/<.*\///g' -e 's/">//g' -e 's/ *//g' | head""" %(CC_BUILD_DETAIL_URL, proj_selected, proj_selected)
    version_folder_list = exec_shell_cmd(get_ver_folder_list_cmd, False)[1]
    version_folder_list = version_folder_list.split('\n') if version_folder_list else []
    version_folder_list = filter(lambda x:x != '', version_folder_list)
    
    get_svn_ver_list_cmd = """wget -q -c -O - %s/%s | grep -e '%s_[[:digit:]].*\+M$' | awk '{print $NF}' | head"""  %(CC_BUILD_DETAIL_URL, proj_selected, proj_selected)
    svn_version_list = exec_shell_cmd(get_svn_ver_list_cmd, False)[1]
    svn_version_list = svn_version_list.split('\n') if svn_version_list else []
    svn_version_list = filter(lambda x:x != '', svn_version_list)
    
    print ""
    for i in range(len(svn_version_list)):
        print "%-2d  :  %-20s" %(i,svn_version_list[i])
    print "-------------------------------"
    print "%-3s :\tClear screen"            %("c")
    print "%-3s :\tList versions again"     %("l")
    print "%-3s :\tQuit to the project menu"   %("q")
        
    while True:
        choice = raw_input("VersionMenu:")
        choice = choice.strip()
        if choice == '':
            continue
        elif choice == 'q' or choice == 'Q':
            break
        elif choice == 'c' or choice == 'C':
            exec_shell_cmd('clear')
        elif choice == 'l' or choice == 'L' or choice == 'h' or choice == 'H':
            print ""
            for i in range(len(svn_version_list)):
                print "%-3d :\t%-20s" %(i,svn_version_list[i])
            print "-------------------------------"
            print "%-3s :\tClear screen"            %("c")
            print "%-3s :\tList versions again"     %("l")
            print "%-3s :\tQuit to the project menu"   %("q")
        elif choice.isdigit() and (0 <= string.atoi(choice) < len(svn_version_list)):
            try:
                #Note,version_folder_list and svn_version_list is corresponding
                ver_folder_selected = version_folder_list[string.atoi(choice)]
            except IndexError:
                print "Wrong index inputed"
                continue
            return action_on_get(target_selected, proj_selected,ver_folder_selected)
        else:
            print "Wrong choice inputed"    

def proj_choice_menu(target_selected):
    if not target_selected or len(target_selected) == 0:
        print "None target is selected!"
        return -1
        
    #Parse proj filter list from file BUILD.sh
    get_filter_list_cmd = """cat %s/BUILD.sh | grep 'CC_FTP_FOLDER=' | sed -e 's/CC_FTP_FOLDER//g' -e 's/\=//g' -e 's/(//g' -e 's/)//g' -e 's/\"//g' | tr -s ' ' | tr -d '\n'""" % os.environ['SCRIPTS_DIR']
    filter_list = exec_shell_cmd(get_filter_list_cmd, False)[1]
    filter_list = filter_list.split(" ")
    filter_list = filter(lambda x: x != '', filter_list)
        
    #Parse project list from the svn webpage
    get_projs_cmd = """wget -q -c -O - %s | grep -e '<span class=\"title wbrSensitive\">.*</span>' | sed -e 's/<.*">//g' -e 's/<\/.*>//g' -e 's/ *//g'""" %(PROJ_BUILDS_URL)
    proj_list = exec_shell_cmd(get_projs_cmd, False)[1]
    proj_list = proj_list.split('\n') if proj_list else []
    if filter_list == None or len(filter_list) == 0:
        proj_list = filter(lambda x: x != '' and x != 'SVN_LOG', proj_list)
    else:
        proj_list = filter(lambda x: x != '' and x != 'SVN_LOG' and x in filter_list, proj_list)
    
    #Print the project list and cmd hint
    print ""
    for i in range(len(proj_list)):
        print "%-3d :\t%-20s" %(i,proj_list[i])
    print "-------------------------------"
    print "%-3s :\tClear screen"            %("c")
    print "%-3s :\tList projects again"     %("l")
    print "%-3s :\tQuit to the main menu"   %("q")
    
    while True:
        choice = raw_input("ProjectMenu:")
        choice = choice.strip()
        if choice == '':
            continue  
        elif choice == 'q' or choice == 'Q':
            break
        elif choice == 'c' or choice == 'C':
            exec_shell_cmd('clear')
        elif choice == 'l' or choice == 'L' or choice == 'h' or choice == 'H':
            print ""
            for i in range(len(proj_list)):
                print "%-3d :\t%-20s" %(i,proj_list[i])
            print "-------------------------------"
            print "%-3s :\tClear screen"            %("c")
            print "%-3s :\tList projects again"     %("l")
            print "%-3s :\tQuit to the main menu"   %("q")
        elif choice.isdigit() and (0 <= string.atoi(choice) < len(proj_list)):
            try:
                proj_selected = proj_list[string.atoi(choice)]
            except IndexError:
                print "Wrong index inputed"
                continue
            return version_choice_menu(target_selected, proj_selected)
        else:
            print "Wrong choice inputed"
            
def target_choice_menu():
    tgt_binary = Target("library",        "lib",    os.environ["HBLIB_PATH"])
    tgt_sys    = Target("sys",            "build",  os.environ["LINK_DIR"])
    tgt_output = Target("upgrade binary", "output", os.environ["OUTPUT_DIR"])
    target_list = [tgt_binary, tgt_sys, tgt_output]
    
    print "\nPlease select targets to get:"
    for i in range(len(target_list)):
        print "%-3d :\t%-20s" %(i, target_list[i].name)
    print "%-3s :\t%-20s" %("a", "Above all")
    
    while True:
        target_selected = []
        choice = raw_input("TargetMenu:")
        choice = choice.strip()
        if choice == '':
            continue  
        elif choice == 'q' or choice == 'Q':
            break
        elif choice == 'c' or choice == 'C':
            exec_shell_cmd('clear')
        elif choice == 'l' or choice == 'L' or choice == 'h' or choice == 'H':
            print "\nPlease select target to get:"
            for i in range(len(target_list)):
                print "%-3d :\t%-20s" %(i, target_list[i].name)
            print "%-3s :\t%-20s" %("a", "ALL")
        elif choice == "a" or choice == 'A':
            target_selected.extend(target_list)
            return proj_choice_menu(target_selected)
        elif choice.isdigit() and (0 <= string.atoi(choice) < len(target_list)):
            try:
                target_selected.append(target_list[string.atoi(choice)])
            except IndexError:
                print "Wrong index inputed"
                continue
            return proj_choice_menu(target_selected)
        else:
            print "Wrong choice inputed"    
    
def main():
    target_choice_menu()

if __name__ == "__main__":
    main()